package com.sci99.ex.util;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import com.sci99.ex.model.Question;

public class ExcelUtil {
	static Logger log = Logger.getLogger(ExcelUtil.class);
	/**
	 * 数据起始位置
	 */
	private static final int start_idx = 6;
	private static final int max_col = 13;

	/**
	 * 导入Excel数据
	 * 
	 * @param is
	 * @return List<Question>
	 * @throws Exception
	 */
	public static List<Question> importData(InputStream is) throws Exception {
		Workbook wb = Workbook.getWorkbook(is);
		Sheet s = wb.getSheet(0);
		List<Question> l = new ArrayList<>();
		int rows = s.getRows();
		for (int i = start_idx; i < rows; i++) {
			Cell[] c = s.getRow(i);
			// log.debug(c.length);
			Question q = new Question();
			switch (max_col - c.length) {
			case 0:
				q.setAnswer6(!isEmpty(c[12]));
			case 1:
				q.setChoice6(c[11].getContents());
			case 2:
				q.setAnswer5(!isEmpty(c[10]));
			case 3:
				q.setChoice5(c[9].getContents());
			case 4:
				q.setAnswer4(!isEmpty(c[8]));
			case 5:
				q.setChoice4(c[7].getContents());
			case 6:
				q.setAnswer3(!isEmpty(c[6]));
			case 7:
				q.setChoice3(c[5].getContents());
			case 8:
				q.setAnswer2(!isEmpty(c[4]));
			case 9:
				q.setChoice2(c[3].getContents());
			case 10:
				q.setAnswer1(!isEmpty(c[2]));
			case 11:
				q.setChoice1(c[1].getContents());
			case 12:
				q.setTitle(c[0].getContents());
			case 13:
			}
			l.add(q);
		}
		return l;
	}

	/**
	 * 判断单元格是否为空
	 * 
	 * @param c
	 * @return
	 */
	private static boolean isEmpty(Cell c) {
		if (c.getContents() == null) {
			return true;
		}
		if (c.getContents().trim().length() == 0)
			return true;
		return false;
	}
}
